package org.mx.notify.processor;

import java.util.ArrayList;
import java.util.List;

import org.mx.StringUtils;
import org.mx.notify.config.NotifyServerConfigBean;
import org.mx.notify.error.UserInterfaceWsNotifyErrorException;
import org.mx.notify.processor.WsMessageProcessor.ProcessedState;
import org.mx.service.server.websocket.WsConnectKey;
import org.mx.service.server.websocket.WsLifeCircleMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * 推送服务器消息处理器
 * 
 * @author john.peng
 *
 */
public class NotifyServerWebSocket extends WsLifeCircleMonitor {
	private static final Logger logger = LoggerFactory.getLogger(NotifyServerWebSocket.class);

	private ApplicationContext applicationContext;
	private NotifyServerConfigBean configBean;
	private List<WsMessageProcessor> processors;

	/**
	 * 构造函数
	 * 
	 * @param context    Spring IoC容器
	 * @param configBean 推送服务器配置信息
	 */
	public NotifyServerWebSocket(ApplicationContext context, NotifyServerConfigBean configBean) {
		super(configBean.getNotifyPath());
		this.applicationContext = context;
		this.configBean = configBean;
	}

	/**
	 * 初始化WebSocket
	 */
	public void init() {
		this.processors = new ArrayList<WsMessageProcessor>();
		String processorNames = configBean.getProcessorNames();
		for (String processorName : StringUtils.split(processorNames)) {
			WsMessageProcessor processor = this.applicationContext.getBean(processorName, WsMessageProcessor.class);
			this.processors.add(processor);
			if (logger.isInfoEnabled()) {
				logger.info(String.format("Load WebSocket processor['%s'] successed.", processorName));
			}
		}
	}

	/**
	 * 销毁申请的资源
	 */
	public void destroy() {
		this.processors.clear();
		this.processors = null;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see WsLifeCircleMonitor#hasText(WsConnectKey, String)
	 */
	@Override
	public void hasText(WsConnectKey connectKey, String messageContext) {
		super.hasText(connectKey, messageContext);
		if (StringUtils.isBlank(messageContext)) {
			if (logger.isWarnEnabled()) {
				logger.warn("The text message is blank.");
			}
			throw new UserInterfaceWsNotifyErrorException(
					UserInterfaceWsNotifyErrorException.WsNotifyErrors.MESSAGE_BLANK);
		} else {
			for (WsMessageProcessor processor : processors) {
				ProcessedState state = processor.process(connectKey, messageContext);
				if (configBean.isQuickMode() && state == ProcessedState.SUCCESS) {
					if (logger.isTraceEnabled()) {
						logger.trace(
								"The message is processed success, and quick mode be set, process chain will be break.");
					}
					break;
				}
			}
		}
	}
}
